<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <!-- <a-col :md="6" :sm="24">
              <a-form-item label="查找学校名称">
                <a-input v-model="queryParam.name" placeholder="请输入" />
              </a-form-item>
            </a-col> -->
            <a-col :md="5" :sm="24">
              <a-form-item label="标签查询">
                <a-select
                v-model="queryParam.id" placeholder="请选择" default-value="1"
                show-search
                option-filter-prop="children"
                :filter-option="filterOption"
                >
                <a-select-option :value="item.id" v-for="(item) in labelList" :key="item.id">
                    {{item.name}}
                </a-select-option>
                </a-select>
            </a-form-item>
            </a-col>
            <a-col :md="(!advanced && 8) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd" v-action:label_add2>新建</a-button>
      </div>

      <s-table ref="table" size="default" rowKey="id" :columns="columns" :data="loadData" showPagination="auto">
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>

        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)" v-action:label_edit2>修改</a>
            <a-divider type="vertical" />
            <a-popconfirm
             v-action:label_del2
              title="确定删除这个角色吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="confirm(record)"
              @cancel="cancel(record)"
            >
              <a>删除</a>
            </a-popconfirm>
            <a-divider type="vertical" v-if="record.pid == 0" v-action:label_add2/>
            <a @click="handleSub(record)" v-if="record.pid == 0" v-action:label_add2>添加子标签</a>
          </template>
        </span>
      </s-table>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
      />
      <updata-form
        ref="updataModal"
        :visible="updata"
        :loading="confirmLoading"
        :model="mdls"
        @cancel="handleUpdataCancel"
        @ok="handleUpdataOk"
      />
      <step-by-step-modal ref="modal" @ok="handleOk" />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { GetLabelList, AddLabel, UpdataLabel, DelLabel } from '../../../api/school'
import { SchoolRecursion } from '../../../api/system'


import StepByStepModal from './modules/StepByStepModal'
import CreateForm from './modules/CreateForm'
import UpdataForm from './modules/UpdataForm'

const columns = [
  {
    title: '标签',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '200px',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'SystemDepartment',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    StepByStepModal,
    UpdataForm,
  },
  data() {
    this.columns = columns
    return {
      labelList: [],
      // updata model
      mdls: {},
      updata: false,
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        return GetLabelList(requestParameters).then((res) => {
          return res.data
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
      }
    },
  },
  created() {
    this.GetSchoolRecursion()
  },
  methods: {
    // 获取学校标签列表
    GetSchoolRecursion() {
      SchoolRecursion().then(res => {
        this.labelList = res.data
      })
    },
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.mdl = { ...record }
    },
    // 添加子标签
    handleSub(record) {
      this.updata = true
      this.mdls = { ...record }
    },
    handleUpdataCancel() {
      this.updata = false
      const form = this.$refs.updataModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleUpdataOk() {
      const form = this.$refs.updataModal.form
      this.confirmLoading = true
      form.validateFields((error, values) => {
        if (!error) {
          console.log('------------------添加子标题values-------------', values)
          const value = { pid: values.id, name: values.name }
          AddLabel(value).then(
            (res) => {
              if( res ) {
                this.updata = false
                this.confirmLoading = false
                // 重置表单数据
                form.resetFields()
                // 刷新表格
                this.$refs.table.refresh()

                this.$message.success('添加子标题成功')
              } else {
              this.confirmLoading = false
              }
            },
          )
        } else {
          this.confirmLoading = false
        }
      })
    },
    // 创建
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('修改', values)
          if (values.id > 0) {
            // 修改 e.g.
            new Promise((resolve, reject) => {
              const value = { id: values.id, name: values.name }
              UpdataLabel(value).then(
                (res) => {
                if( res ){
                    resolve()
                  }else{
                    this.confirmLoading = false
                  }
                },
              )
            }).then((res) => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('修改成功')
            })
          } else {
            // 新增
            new Promise((resolve, reject) => {
              const value = { name: values.name, pid: 0 }
              AddLabel(value).then(res => {
                console.log('value', res)
                if( res ){
                  resolve()
                }else{
                  this.confirmLoading = false
                }
              })
            }).then((res) => {
              console.log(res);
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()
              this.$message.success('新增成功')
            })
          }
        }
      })
    },
    // 删除
    confirm(e) {
      const form = this.$refs.createModal.form
      console.log(e)
      DelLabel({ id: e.id })
        .then((res) => {
          // 重置表单数据
          form.resetFields()
          // 刷新表格
          this.$refs.table.refresh()
          this.$message.success('删除成功')
        })
        .catch((error) => {
          console.log('-------------error------------', error)
        })
    },
    cancel(e) {
      console.log(e)
      this.$message.error('已取消')
    },
    handleCancel() {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    // 启用
    handleEnable(record) {},
    // 禁用
    handleDisable(record) {},
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date()),
      }
    },
    // 重置
    reset() {
      const form = this.$refs.createModal.form
      this.queryParam = {}
      // 重置表单数据
      form.resetFields()
      // 刷新表格
      this.$refs.table.refresh()
    },
        // 搜素模糊查询
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
          )
        }
  },
}
</script>
